package com.xlongwei.info;

import java.util.Collections;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.utility.StringUtils;
import com.xlongwei.info.hook.Startup;
import com.xlongwei.info.model.Info;
import com.xlongwei.info.model.User;
import com.xlongwei.info.util.InfoConfig;
import com.xlongwei.info.util.Infos;
import com.xlongwei.info.util.Users;
import com.xlongwei.info.util.Utils;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonHandler implements HttpHandler {
	private final ObjectMapper objectMapper;

	public JsonHandler(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	public void handleRequest(HttpServerExchange exchange) throws Exception {
		String action = Utils.getParam(exchange, "action");
		Map<String, Object> map = Utils.getMap(exchange);
		String token = (String) map.get("token");
		String username = Utils.username(token);
		log.info("action={} token={} user={}", action, token, username);
		User operator = Users.user(username);
		if (StringUtils.isBlank(action) || StringUtils.isBlank(username) || operator == null || operator.isBan()) {
			answerJson(exchange, Collections.singletonMap("error", "没有权限"));
		} else if ("info".equals(action)) {
			Info info = Info.builder().user(Utils.firstNotBlank((String) map.get("user"), username))
					.from((String) map.get("from")).to((String) map.get("to")).owner(Utils.toBoolean(map.get("owner")))
					.note((String) map.get("note")).start(Utils.toLocalDateTime(map.get("start")))
					.end(Utils.toLocalDateTime(map.get("end"))).build();
			log.info("info={}", info);
			String check = Infos.store(info);
			if (StringUtils.isBlank(check)) {
				Utils.notify(info);
				answerJson(exchange, Collections.emptyMap());
			} else {
				answerJson(exchange, Collections.singletonMap("error", check));
			}
		} else if ("delete".equals(action)) {
			delete(exchange, map, operator);
		} else if ("ban".equals(action) && InfoConfig.INSTANCE.isAdmin(operator.getUser())) {
			ban(exchange, map, operator);
		} else if ("owner".equals(action) && InfoConfig.INSTANCE.isAdmin(operator.getUser())) {
			owner(exchange, map, operator);
		} else if ("infos".equals(action) && InfoConfig.INSTANCE.isAdmin(operator.getUser())) {
			answerJson(exchange, Collections.singletonMap("infos", Infos.infos()));
		} else if ("users".equals(action) && InfoConfig.INSTANCE.isAdmin(operator.getUser())) {
			answerJson(exchange, Collections.singletonMap("users", Users.users()));
		} else if ("accept".equals(action)) {
			accept(exchange, map, operator);
		} else if ("reload".equals(action) && InfoConfig.INSTANCE.isAdmin(operator.getUser())) {
			answerJson(exchange, Collections.singletonMap("reload", InfoConfig.reload()));
			Startup.loadConfig();
		} else {
			answerJson(exchange, Collections.singletonMap("error", "没有权限"));
		}
	}

	private void delete(HttpServerExchange exchange, Map<String, Object> map, User operator) throws Exception {
		String user = (String) map.get("user");
		Info info = Infos.info(Utils.firstNotBlank(user, operator.getUser()));
		String delete = Infos.delete(operator, info);
		if (StringUtils.isBlank(delete)) {
			Utils.notify(Info.builder().user(info.getUser()).owner(info.isOwner()).build());
			answerJson(exchange, Collections.singletonMap("delete", info));
		} else {
			answerJson(exchange, Collections.singletonMap("error", delete));
		}
	}

	private void ban(HttpServerExchange exchange, Map<String, Object> map, User operator) throws Exception {
		String user = (String) map.get("user");
		String ban = Users.ban(user);
		if (StringUtils.isBlank(ban)) {
			answerJson(exchange, Collections.singletonMap("ban", Users.user(user).isBan()));
		} else {
			answerJson(exchange, Collections.singletonMap("error", ban));
		}
	}
	
	private void owner(HttpServerExchange exchange, Map<String, Object> map, User operator) throws Exception {
		String user = (String) map.get("user");
		String error = Users.owner(operator, user);
		if (StringUtils.isBlank(error)) {
			answerJson(exchange, Collections.singletonMap("owner", Users.user(user).isOwner()));
		} else {
			answerJson(exchange, Collections.singletonMap("error", error));
		}
	}

	private void accept(HttpServerExchange exchange, Map<String, Object> map, User operator) throws Exception {
		String user = (String) map.get("user");
		String accept = Users.accept(operator, user);
		if (StringUtils.isBlank(accept)) {
			Info info = Infos.info(user);
			Utils.notify(info);
			boolean b = info.getAcceptors().contains(operator.getUser());
			answerJson(exchange, Collections.singletonMap("accept", b));
		} else {
			answerJson(exchange, Collections.singletonMap("error", accept));
		}
	}

	private void answerJson(HttpServerExchange exchange, Object obj) throws Exception {
		exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
		exchange.getResponseSender().send(objectMapper.writeValueAsString(obj));
	}
}
